//
//  HotSoundDetailsViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/22.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "HotSoundDetailsViewController.h"
#import "AlbumDatailsOfList.h"
#import "AlbumDetailsCell.h"
#import "NetHandler.h"
#import "HomeInformationDetail.h"
#import "MainPlayerViewController.h"
// 导入刷新的头文件
#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"


#import "MainPlayerViewController.h"

#import "AudioPlayer.h"
#import "AudioButton.h"

@interface HotSoundDetailsViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *hotTableView;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UISegmentedControl *hotSegment;

// segment的三个数组
@property (nonatomic, retain) NSMutableArray *dailyArr;
@property (nonatomic, retain) NSMutableArray *hotArr;
@property (nonatomic, retain) NSMutableArray *favoArr;

@property (nonatomic, retain) MainPlayerViewController *mainPlay;

@property(nonatomic, retain) UIView *myView;


@property (nonatomic, assign) NSInteger cellTag;

@property (nonatomic, retain)AlbumDetailsCell *cell;

@property (nonatomic, retain)AudioButton *audioBtn;

@property(nonatomic, retain) MainPlayerViewController *mainPlayVC;

// 当前hot请求页数
@property (nonatomic, assign) NSInteger hotPageId;

// 当前daily请求页数
@property (nonatomic, assign) NSInteger dailyPageId;

// 当前favo请求页数
@property (nonatomic, assign) NSInteger favoPageId;

@end

@implementation HotSoundDetailsViewController


- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.hotTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.hotTableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.hotTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self.view addSubview:self.myView];
    
    //1. 在这调用请求网络数据方法（刷新数据）
    if (self.hotSegment.selectedSegmentIndex == 0) {
        self.dailyPageId = 1;
        [self.dailyArr removeAllObjects];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=daily&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSMutableArray *array = [result objectForKey:@"list"];
            
            for (NSDictionary *dic in array) {
                AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                [self.dailyArr addObject:datailList];
                [datailList release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.dailyArr];
            
            [self.hotTableView reloadData];
            
        }];
        
    } else if (self.hotSegment.selectedSegmentIndex == 1) {
        self.hotPageId = 1;
        [self.hotArr removeAllObjects];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=hot&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
        
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = [result objectForKey:@"list"];
            
            for (NSDictionary *dic in array) {
                AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                [self.hotArr addObject:datailList];
                [datailList release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.hotArr];
            [self.hotTableView reloadData];
            
        }];
        
    } else {
        
        self.favoPageId = 1;
        [self.favoArr removeAllObjects];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=favorite&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = [result objectForKey:@"list"];
            
            for (NSDictionary *dic in array) {
                AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                [self.favoArr addObject:datailList];
                [datailList release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.favoArr];
            [self.hotTableView reloadData];
            
        }];
        
    }
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        //[self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hotTableView headerEndRefreshing];
        [self.myView removeFromSuperview];
    });
    
}

#pragma mark 进入加载状态
- (void)footerRereshing
{
    
    //1. 拼接口等操作
    // 请求加载数据
    //1. 在这调用请求网络数据方法（刷新数据）
    if (self.hotSegment.selectedSegmentIndex == 0) {
        
        if (self.dailyPageId < 50) {
            
            self.dailyPageId++;
            
            NSString *pageId = [NSString stringWithFormat:@"%ld", self.dailyPageId];
            
            NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=daily&device=iPhone&page=%@&per_page=20&tag_name=", self.homeInformationDetail.name, pageId];
            
            [NetHandler getDataWithURL:str completion:^(NSData *data) {
                
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *array = [result objectForKey:@"list"];
                
                for (NSDictionary *dic in array) {
                    AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                    [self.dailyArr addObject:datailList];
                    [datailList release];
                    
                }
                [self.arr removeAllObjects];
                [self.arr addObjectsFromArray:self.dailyArr];
                
                [self.hotTableView reloadData];
                
            }];
 
        }
        
        
    } else if (self.hotSegment.selectedSegmentIndex == 1) {
        
        if (self.hotPageId < 50) {
            self.hotPageId++;
            
            NSString *pageId = [NSString stringWithFormat:@"%ld", self.hotPageId];
            
            NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=hot&device=iPhone&page=%@&per_page=20&tag_name=", self.homeInformationDetail.name, pageId];
            
            
            [NetHandler getDataWithURL:str completion:^(NSData *data) {
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *array = [result objectForKey:@"list"];
                
                for (NSDictionary *dic in array) {
                    AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                    [self.hotArr addObject:datailList];
                    [datailList release];
                    
                }
                [self.arr removeAllObjects];
                [self.arr addObjectsFromArray:self.hotArr];
                [self.hotTableView reloadData];
                
            }];

            
        }
        
        
        
    } else {
        
        if (self.favoPageId < 50) {
            
            self.favoPageId++;
            NSString *pageId = [NSString stringWithFormat:@"%ld", self.favoPageId];
            
            NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=favorite&device=iPhone&page=%@&per_page=20&tag_name=", self.homeInformationDetail.name, pageId];
            
            [NetHandler getDataWithURL:str completion:^(NSData *data) {
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray *array = [result objectForKey:@"list"];
                
                for (NSDictionary *dic in array) {
                    AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
                    [self.favoArr addObject:datailList];
                    [datailList release];
                    
                }
                [self.arr removeAllObjects];
                [self.arr addObjectsFromArray:self.favoArr];
                [self.hotTableView reloadData];
                
            }];
            

            
            
        }
        
            }

    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.hotTableView reloadData];
        [self.hotTableView footerEndRefreshing];
    });
    
}

#pragma mark 数据解析
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=daily&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [result objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
            [self.dailyArr addObject:datailList];
            [datailList release];
            
        }
        [self.arr addObjectsFromArray:self.dailyArr];
        
        
        [self.hotTableView reloadData];
       
    }];
    
}

#pragma mark 本周热门
- (void)hotHandleData
{
     NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=hot&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
  
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [result objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
            [self.hotArr addObject:datailList];
            [datailList release];
            
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.hotArr];
        [self.hotTableView reloadData];
        
    }];
}

#pragma mark 最多赞
- (void)likeHandleData
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_track_list?category_name=%@&condition=favorite&device=iPhone&page=1&per_page=20&tag_name=", self.homeInformationDetail.name];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [result objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            AlbumDatailsOfList *datailList = [[AlbumDatailsOfList alloc] initWithDictionary:dic];
            [self.favoArr addObject:datailList];
            [datailList release];
            
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.favoArr];
        [self.hotTableView reloadData];
        
    }];
}



#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
        
        self.dailyArr = [NSMutableArray array];
        self.hotArr = [NSMutableArray array];;
        self.favoArr = [NSMutableArray array];
        
        self.hotPageId = 1;
        self.dailyPageId = 1;
        self.favoPageId = 1;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.homeInformationDetail.title;
    
    self.myView = [[UIView alloc] initWithFrame:self.view.frame];
    self.myView.userInteractionEnabled = YES;
    self.myView.backgroundColor = [UIColor clearColor];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 数据处理
   // [self handleData];
    
    // Do any additional setup after loading the view.
    
    
    
    self.hotTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    // 设置代理
    self.hotTableView.delegate = self;
    self.hotTableView.dataSource = self;
    // 设置tableView的header的高
    self.hotTableView.sectionHeaderHeight = 40;
    [self.view addSubview:self.hotTableView];
    [_hotTableView release];
    // hottableView 注册cell
    [self.hotTableView registerClass:[AlbumDetailsCell class] forCellReuseIdentifier:@"hot"];
    
    
    // 设置segment
    self.hotSegment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"最火",@"本周热门",@"最多赞", nil]];
    self.hotSegment.selectedSegmentIndex = 0;
    self.hotSegment.alpha = 1;
    self.hotSegment.backgroundColor = [UIColor clearColor];
    
    self.hotSegment.frame = CGRectMake(0, 5, self.view.frame.size.width, 30);
    [self.hotSegment addTarget:self action:@selector(changeSegment:) forControlEvents:UIControlEventValueChanged];
    [_hotSegment release];
    
    // 调用下拉帅新 上拉加载
    [self setupRefresh];
    
}

#pragma mark 设置segment
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    [sectionView setBackgroundColor:[UIColor whiteColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.hotSegment];
    
    return sectionView;
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"section:%ld", section];
}

#pragma mark segment点击方法
- (void)changeSegment:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.dailyArr];
        [self.hotTableView reloadData];
        
    } else if (segment.selectedSegmentIndex == 1) {
        
        if (self.hotArr.count == 0) {
            [self hotHandleData];
        } else {
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.hotArr];
            [self.hotTableView reloadData];
            
        }
 
    } else if (segment.selectedSegmentIndex == 2) {
        
        if (self.favoArr.count == 0) {
            [self likeHandleData];
        } else {
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.favoArr];
            [self.hotTableView reloadData];
            
        }
        
        
        
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

#pragma mark cell设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *str = @"datails";
    
    AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil || self.cellTag != (self.hotSegment.selectedSegmentIndex + 1) * 10000 + indexPath.row) {
        
        cell = [[[AlbumDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
        [cell.audioButton addTarget:self action:@selector(playTheAudio:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.audioButton.tag = indexPath.row + (self.hotSegment.selectedSegmentIndex + 1) * 10000;
    
    if (self.cellTag == (self.hotSegment.selectedSegmentIndex + 1) * 10000 + indexPath.row) {
        [cell.audioButton removeFromSuperview];
        [cell.contentView addSubview:self.audioBtn];
    }
    AlbumDatailsOfList *datailList = [self.arr objectAtIndex:indexPath.row];
    
    NSLog(@"%ld",cell.tag);
    
    
    cell.albumDatailsOfList = datailList;
    
    return cell;
    
    
    
//    AlbumDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hot"];
//    AlbumDatailsOfList *dataiList = [self.arr objectAtIndex:indexPath.row];
//    cell.albumDatailsOfList = dataiList;
//    
//    return cell;
}

    
    
    
#pragma mark 点击播放的按钮
    
- (void)playTheAudio:(AudioButton *)button
{
        self.audioBtn = button;
        self.cellTag = button.tag;
        _audioPlayer =  [AudioPlayer shareInstance];
    _audioPlayer.imagePath = [[self.arr objectAtIndex:button.tag - (self.hotSegment.selectedSegmentIndex + 1) * 10000] coverLarge];
        if ([_audioPlayer.button isEqual: button]) {
            
            [_audioPlayer play];
    
        } else {
            
            _mainPlayVC = [MainPlayerViewController defaultPlayer];
            [_mainPlayVC.listArr removeAllObjects];
            [_mainPlayVC.listArr addObjectsFromArray:self.arr];
            _mainPlayVC.trackId = [NSNumber numberWithFloat:[[[self.arr objectAtIndex:button.tag - (self.hotSegment.selectedSegmentIndex + 1) * 10000] id] floatValue]];
            [_mainPlayVC showDetailInformation];
            [_audioPlayer stop];
            
            _audioPlayer.button = button;
            
            _audioPlayer.url = [NSURL URLWithString:[[self.arr objectAtIndex:button.tag - (self.hotSegment.selectedSegmentIndex + 1) * 10000] playUrl64] ];
            
            [_audioPlayer play];
        }
}

    
#pragma mark cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    self.cell = (AlbumDetailsCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    AlbumDatailsOfList *dataList = [self.arr objectAtIndex:indexPath.row];
    
    _mainPlayVC = [MainPlayerViewController defaultPlayer];
    
    _mainPlayVC.albumDatail = dataList;
    _mainPlayVC.trackId = [NSNumber numberWithInteger: [dataList.id integerValue]];
    _audioPlayer = [AudioPlayer shareInstance];
    NSLog(@"%@",_mainPlayVC.listArr);
    [_mainPlayVC.listArr removeAllObjects];
    [_mainPlayVC.listArr addObjectsFromArray:self.arr];
    NSLog(@"%@", _mainPlayVC.listArr);
    _mainPlayVC.index = indexPath.row;
    _mainPlayVC.navi = self.navigationController;
    
    if (![_audioPlayer.button isEqual:_cell.audioButton]) {
        
        [_audioPlayer stop];
        self.audioBtn = _cell.audioButton;
        _audioPlayer.button = _cell.audioButton;
        self.cellTag = _cell.audioButton.tag;
        _audioPlayer.url = [NSURL URLWithString:dataList.playUrl64];
        [_audioPlayer play];
        
    }
    
    
    // _mainPlayVC.audioButton = _cell.audioButton;
    
    [_mainPlayVC showDetailInformation];
    
//    [self presentViewController:_mainPlayVC animated:YES completion:^{
//        
//        
//    }];
    // push推出主播放页面
    CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"push";
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [self.navigationController pushViewController:_mainPlayVC animated:NO];
    
    
//    AlbumDatailsOfList *dataList = [self.arr objectAtIndex:indexPath.row];
//    _mainPlay = [MainPlayerViewController defaultPlayer];
//    _mainPlay.albumDatail = dataList;
//    [_mainPlay showDetailInformation];
//    [self.navigationController pushViewController:_mainPlay animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

#pragma mark 释放
- (void)dealloc
{
    [_hotSegment release];
    [_favoArr release];
    [_hotTableView release];
    [_dailyArr release];
    [_arr release];
    [_myView release];
    [_hotArr release];
    [_myView release];

    [_mainPlay release];
    [_cell release];
    [_audioBtn release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
